import { useState, useMemo } from 'react';
import type { ComplianceItem, RiskAssociationFilters, RiskAssociationStats } from '@/types/work';
import { ViewMode, RiskFilterTab, RiskLevel } from '@/types/work';
import { 
  RiskAssuranceHeader, 
  RiskAssuranceFilters, 
  RiskMatrixView, 
  RiskList,
  AssociationDialog
} from '@/components/work';
import { useComplianceStore } from '@/stores/useComplianceStore';
import { sortComplianceItems } from '@/utils/utils';

/**
 * 风险-保障关联视图组件
 */
const RiskView = () => {
  const {
    items,
    getRiskItems,
    getGuaranteeItems,
    updateRiskAssociations,
    removeAssociation
  } = useComplianceStore();
  
  // 本地状态
  const [filters, setFilters] = useState<RiskAssociationFilters>({
    tab: RiskFilterTab.ALL,
    searchTerm: '',
    viewMode: ViewMode.MATRIX
  });
  
  const [dialogOpen, setDialogOpen] = useState(false);
  const [selectedRisk, setSelectedRisk] = useState<ComplianceItem | null>(null);
  
  // 获取风险项和保障项
  const riskItems = useMemo(() => getRiskItems(), [items, getRiskItems]);
  const guaranteeItems = useMemo(() => getGuaranteeItems(), [items, getGuaranteeItems]);
  
  // 计算过滤后的风险项
  const filteredRiskItems = useMemo(() => {
    return sortComplianceItems(riskItems.filter(risk => {
      // 按搜索词过滤
      if (filters.searchTerm && !risk.title.toLowerCase().includes(filters.searchTerm.toLowerCase())) {
        return false;
      }
      
      // 首先过滤出高中风险
      const isHighOrMediumRisk = risk.risk_level === RiskLevel.HIGH || risk.risk_level === RiskLevel.MEDIUM;
      if (!isHighOrMediumRisk) {
        return false;
      }

      // 按标签页过滤
      if (filters.tab === RiskFilterTab.UNASSOCIATED) {
        return !risk.related_guarantees || risk.related_guarantees.length === 0;
      } else if (filters.tab === RiskFilterTab.HIGH || filters.tab === RiskFilterTab.MEDIUM) {
        // 转换RiskFilterTab为RiskLevel进行比较
        const riskLevelMap: Record<string, RiskLevel> = {
          [RiskFilterTab.HIGH]: RiskLevel.HIGH,
          [RiskFilterTab.MEDIUM]: RiskLevel.MEDIUM
        };
        return risk.risk_level === riskLevelMap[filters.tab];
      }
      
      // 全部高中风险（ALL）的情况
      return true;
    }));
  }, [riskItems, filters.searchTerm, filters.tab]);
  
  // 计算统计信息
  const stats: RiskAssociationStats = useMemo(() => {
    // 先过滤出高中风险项
    const highMediumRisks = riskItems.filter(
      risk => risk.risk_level === RiskLevel.HIGH || risk.risk_level === RiskLevel.MEDIUM
    );
    
    // 计算高中风险项的总数
    const totalRisks = highMediumRisks.length;
    
    // 计算已关联的高中风险项数量
    const associatedRisks = highMediumRisks.filter(
      r => r.related_guarantees && r.related_guarantees.length > 0
    ).length;
    
    // 计算高中风险项的覆盖率
    const coverageRate = totalRisks > 0 ? Math.round((associatedRisks / totalRisks) * 100) : 0;
    
    // 计算高中风险项的总关联数
    const totalAssociations = highMediumRisks.reduce(
      (sum, risk) => sum + (risk.related_guarantees?.length || 0), 
      0
    );
    
    return {
      totalRisks,
      associatedRisks,
      totalAssociations,
      coverageRate
    };
  }, [riskItems]);
  
  // 处理过滤器变化
  const handleFilterChange = (newFilters: Partial<RiskAssociationFilters>) => {
    setFilters(prev => ({
      ...prev,
      ...newFilters
    }));
  };
  
  // 重置过滤器
  const resetFilters = () => {
    setFilters({
      tab: RiskFilterTab.ALL,
      searchTerm: '',
      viewMode: ViewMode.MATRIX
    });
  };
  
  const handleManageAssociations = (risk: ComplianceItem) => {
    setSelectedRisk(risk);
    setDialogOpen(true);
  };
  
  const handleSaveAssociations = async (riskId: string, guaranteeIds: string[]) => {
    await updateRiskAssociations(riskId, guaranteeIds);
    setDialogOpen(false);
    setSelectedRisk(null);
  };
  
  const handleCloseDialog = () => {
    setDialogOpen(false);
    setSelectedRisk(null);
  };
  
  // 处理关联操作
  const handleRemoveAssociation = async (riskId: string, guaranteeId: string) => {
    await removeAssociation(riskId, guaranteeId);
  };
  
  return (
    <>
      <RiskAssuranceHeader stats={stats} />
      
      <div className="mt-6">
        <RiskAssuranceFilters
          filters={filters}
          setFilters={handleFilterChange}
          resetFilters={resetFilters}
        />
        
        <div className="mt-6">
          {filters.viewMode === ViewMode.MATRIX ? (
            <RiskMatrixView 
              risks={filteredRiskItems}
              guaranteeItems={guaranteeItems}
              onRemoveAssociation={handleRemoveAssociation}
              onManageAssociations={handleManageAssociations}
            />
          ) : (
            <RiskList 
              risks={filteredRiskItems}
              onManageAssociations={handleManageAssociations}
            />
          )}
        </div>
      </div>
      
      <AssociationDialog
        isOpen={dialogOpen}
        onClose={handleCloseDialog}
        risk={selectedRisk}
        guaranteeItems={guaranteeItems}
        onSave={handleSaveAssociations}
      />
    </>
  );
};

export default RiskView; 